<?php

namespace apiend\models\forms;

use Yii;
use apiend\models\User;

/**
 * 帐号密码登录
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class LoginForm extends \common\models\LoginBaseModel {

    /**
     * @var string 用户名
     */
    public $username;

    /**
     * @var string 密码
     */
    public $password;

    /**
     * @var \common\models\app\AppToken 客户端Token信息模型
     */
    public $token = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['username', 'password'], 'required'],
            ['password', 'validatePassword'],
        ];
    }

    /**
     * 校验密码是否正确
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params) {
        if ($this->hasErrors()) {
            return;
        }
        $user = $this->getUser();
        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError($attribute, '输入的用户名或者密码错误');
        }
    }

    /**
     * 设置用户信息
     * @return \apiend\models\User|null
     */
    protected function setUser() {
        return User::findByAccount($this->username);
    }

    /**
     * 用户登录
     * @return bool whether the user is logged in successfully
     */
    public function login() {
        if (!$this->validate()) {
            $this->dumpError('');
        }
        return $this->getUser()->meta;
    }

}
